<template>
  <view class="search-container" :style="listHeightStylePage">
    <up-navbar title="查询聊天记录" @leftClick="searchforclose" placeholder></up-navbar>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <up-input v-model="searchKeyword" placeholder="搜索" prefixIcon="search"
        prefixIconStyle="font-size: 22px;color: #909399;" @change="handleSearch"></up-input>
    </view>

    <!-- 筛选区域 -->
    <view class="search-filter">
      <view class="filter-container">
        <view class="date-picker-wrapper">
          <uni-datetime-picker type="daterange" v-model="selectedDateRange" @change="handleDateChange" :border="false"
            class="compact-date-picker">
          </uni-datetime-picker>
        </view>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view style="padding-right: 20rpx;padding-left: 20rpx;padding-top: 20rpx;">
      <scroll-view :refresher-background="'transparent'" class="search-result" :style="listHeightStyle" scroll-y="true"
        :refresher-enabled="true" :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh"
        @scrolltolower="loadMore">
        <view v-if="searchKeyword && searchResults.length === 0" class="no-result">
          <text>未找到相关记录</text>
        </view>
        <view v-else-if="searchResults.length > 0" class="result-list">
          <view v-for="(item, index) in searchResults" :key="index" class="result-item">
            <!-- 头像和发送人 -->
            <view class="result-header">
              <view class="result-avatar">
                <image v-if="item.fromavatar" :src="item.fromavatar" class="avatar-circle"></image>
                <view v-else class="avatar-circle">{{ showUserName(item.fromname) }}</view>
              </view>
              <view class="result-sender">
                <text class="sender-name">{{ item.fromname }} → {{ item.toname }}</text>
                <text class="sender-time">{{ item.sendtime }}</text>
              </view>
            </view>

            <!-- 消息内容 -->
            <view class="result-content-box">
              <!-- 文本消息 -->
              <template v-if="item.type === 'text'">
                <up-parse :content="item.content"></up-parse>
              </template>

              <!-- 图片消息 -->
              <template v-else-if="item.type === 'img'">
                <up-parse :content="item.content"></up-parse>
              </template>

              <!-- 图片消息 -->
              <template v-else-if="item.type === 'img/text'">
                <up-parse :content="item.content"></up-parse>
              </template>

              <!-- 文件消息 -->
              <template v-else-if="item.type === 'file'">
                <view class="file-message" @click="openDoc(item)">
                  <view class="file-logo">
                    <image :src="`/static/fileType_big/${setFileIcon(item.name)}_b.png`" mode="widthFix"
                      style="width: 50rpx;"></image>
                  </view>
                  <view class="file-name">
                    <view>{{ truncateMiddle(item.name) }}</view>
                    <text>{{ item.formatSize }}</text>
                  </view>
                </view>
              </template>

              <template v-if="item.type === 'apply'" class="chat-apply">
                <view class="apply-card">
                  <view class="applytitle">
                    <view>
                      审批
                    </view>
                    <!-- <view class="apply-status" :class="`applystatus-${item.apply.status}`">
                      {{ getStatusText(item.apply.status) }}
                    </view> -->
                  </view>
                  <view class="apply-header">
                    <view class="apply-title">{{ item.apply.title }}</view>

                  </view>
                  <view class="apply-footer" @click="viewApplyDetail(item.apply.id)">查看详情</view>
                </view>
              </template>

              <view v-if="item.type === 'apply_urge'" class="apply_urge">
                <view class="applyurge-card" @click="viewApplyDetail(item.content.id)">
                  <view class="applyurgetitle"> {{ item.content.title }} </view>
                  <!-- 标题和状态 -->
                  <view class="applyurge-header">
                    <view style="padding-right: 5px;">
                      <image style="width: 45px;height: 45px;" src="@/static/appy-icon/download.png" alt="" />
                    </view>
                    <view class="applyurge-title">{{ item.content.content }}</view>
                  </view>
                </view>
              </view>

              <view v-if="item.type === 'apply_mention'" class="apply_mention">
                <view class="applymention-card" @click="viewApplyDetail(item.content.id)">
                  <view class="applymention-Title">
                    审批
                  </view>
                  <view class="applymentiontitle"> {{ item.content.title }} </view>
                  <!-- 标题和状态 -->
                  <view class="applymention-header">
                    <view class="applymention-title">{{ item.content.content }}</view>
                  </view>
                </view>
              </view>


              <view v-if="item.type === 'log'" class="chat-log">
                <view class="log-card">
                  <view class="log-bg">
                    <view class="log-title-top">日志</view>
                  </view>
                  <view class="log-title">{{ item.content.title }}</view>
                  <!-- <view class="log-content"> -->
                  <!-- <up-parse :content="item.content.content"></up-parse> -->
                  <!-- </view> -->
                  <view class="detail-btn" @click="viewLogDetail(item)">
                    查看详情
                  </view>
                </view>
              </view>

              <view v-if="item.type === 'notice'" class="chat-notice">
                <view class="public-notice-card">
                  <view class="notice-tag">公告</view>
                  <view class="notice-title">{{ item.content.title }}</view>
                  <!-- <view class="notice-image">
                    <image :src="'../../../../static/chat/gonggao.png'" mode="widthFix"></image>
                    <text class="image-text">{{ item.content.title }}</text>
                  </view> -->
                  <view class="notice-content">{{ item.content.content }}</view>
                  <!-- <view class="detail-btn" @click="viewNoticeDetail(item)">
                    查看详情
                  </view> -->
                </view>
              </view>

              <!-- 默认文本显示 -->
              <template v-else>
                <text class="result-content">{{ item.text }}</text>
              </template>
            </view>
          </view>
        </view>
        <view v-else class="no-result">
          <text>未找到相关记录</text>
        </view>

        <!-- 加载中提示 -->
        <view v-if="loading" class="loading-text">
          加载中...
        </view>

        <!-- 没有更多数据提示 -->
        <view v-if="noMore" class="no-more-text">
          没有更多数据了
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { chatApi } from '@/apis/cloud/chat'
import graceRichText from "../config/rich-text-format.js"
import { useChatStore, useSocketStore, useUserStore } from '@/pinia-store/user'
import { fileTypeFormat } from "@/utils/chat"
import { mapStores } from 'pinia'
export default {
  name: "SingleChatRecord",
  data () {
    return {
      searchKeyword: '',
      selectedTimeRange: '',   // 已选择的时间范围，如“最近一周”
      searchResults: [], // 搜索结果
      Chatarray: [],
      friend: null,
      imInfo: null,
      userInfo: null,
      dialogId: null,
      listHeight: 0, // 动态计算的高度
      listHeightStyle: {}, // 动态计算的样式
      topHeight: 0,
      listHeightStylePage: {},
      datetimesingle: '',
      selectedDateRange: [], // 存储选中的日期范围 ['2025-08-11', '2025-08-12']
      formattedDateRange: '', // 格式化后的时间范围
      isRefreshing: false,
      page: 1,
      loading: false,
      noMore: false,
      nextCloud: {}
    }
  },
  computed: {
    ...mapStores(useChatStore, useUserStore, useSocketStore),
  },
  watch: {
    selectedDateRange (value) {
      if (value.length == 0) {
        this.handleSearch(this.searchKeyword);
      }

    }
  },
  onLoad () {
    this.friend = this.chatStore.chat;// 当前聊天对象信息
    this.imInfo = this.chatStore.imInfo;// 当前登录用户
    this.userInfo = this.userStore.user;
    this.dialogId = this.socketStore.nowDialogId;
    this.Getxiaoxi()
  },
  created () {
    this.nextCloud = uni.getStorageSync('next_cloud');
    // #ifdef H5
    this.listHeightStylePage = {
      height: `${window.innerHeight}px`,
    };
    // #endif

    // #ifdef APP-PLUS
    const res = uni.getSystemInfoSync();
    this.listHeight = res.windowHeight;
    this.listHeightStylePage = {
      height: `${res.windowHeight}px`,
    };

    // #endif
    this.calculateListHeight()
  },
  methods: {
		viewLogDetail(value){
      uni.navigateTo({
        url: `/pages/chatlog/index?id=${value.id}`,
      });
		},
    viewNoticeDetail () {
      console.log('公告')
    },
    getStatusText (status) {
      switch (status) {
        case 1: return '审批中';
        case 2: return '已通过';
        case 3: return '已拒绝';
        case 4: return '已撤销';
        default: return '';
      }
    },
    viewApplyDetail (id) {
      uni.navigateTo({
        url: `/pages/apply/oaList/applyOrderDetail?id=${id}`
      })

    },
    truncateMiddle (text, maxLength = 20) {
      if (text.length <= maxLength) return text;
      const half = Math.floor(maxLength / 2);
      return `${text.slice(0, half)}...${text.slice(-half)}`;
    },
    selectTimeRange () {
      this.showTimePopup = true;
    },
    handleDateChange (e) {
      if (Array.isArray(e) && e.length === 2) {
        this.selectedDateRange = e;
        this.formattedDateRange = this.formatDateRangeForDisplay(e);
        this.filterMessages();
      } else {
        this.filterMessages();
        this.selectedDateRange = [];
        this.formattedDateRange = '';
        this.searchResults = this.processAllMessages();
      }
    },
    formatDateRangeForDisplay (dateRange) {
      if (!dateRange || dateRange.length !== 2) return '';

      const format = (dateStr) => {
        const date = new Date(dateStr);
        return `${date.getMonth() + 1}月${date.getDate()}日`;
      };

      return `${format(dateRange[0])}-${format(dateRange[1])}`;
    },
    filterMessages () {
      if (!this.selectedDateRange || this.selectedDateRange.length !== 2) {
        return;
      }

      const [start, end] = this.selectedDateRange;
      const startDate = new Date(start);
      const endDate = new Date(end);
      endDate.setDate(endDate.getDate() + 1); // 包含结束日期当天

      // 过滤原始数据
      const filtered = this.Chatarray.filter(item => {
        const sendTime = new Date(item.send_time);
        return sendTime >= startDate && sendTime < endDate;
      });

      // 临时替换Chatarray为过滤后的结果
      const originalChatArray = this.Chatarray;
      this.Chatarray = filtered;

      // 处理并显示结果
      this.searchResults = this.processAllMessages();

      // 恢复原始数据
      this.Chatarray = originalChatArray;

      // 如果有关键词，需要重新应用关键词过滤
      if (this.searchKeyword) {
        this.handleSearch(this.searchKeyword);
      }
    },
    // 预览图片
    previewImage (content) {
      // 从富文本中提取图片URL
      const imgMatch = content.match(/src="([^"]+)"/);
      if (imgMatch && imgMatch[1]) {
        const imgUrl = imgMatch[1];
        uni.previewImage({
          urls: [imgUrl], // 支持多图预览，这里用单图
          current: 0
        });
      }
    },
    calculateListHeight () {
      const windowHeight = window.innerHeight; // 视口高度
      const topHeight = this.topHeight || 0; // 顶部安全高度
      const navbarHeight = 41; // 导航栏高度（假设为 44px）
      const tabsHeight = 120;
      // #ifdef APP-PLUS
      this.listHeightStyle = {
        height: `${this.listHeight - 190}px`,
      };
      // #endif

      // #ifdef H5
      const listHeight = windowHeight - topHeight - navbarHeight - tabsHeight;
      this.listHeightStyle = {
        height: `${listHeight}px`,
        overflowY: 'hidden',

      };
      // #endif
    },
    // 文件图标处理
    setFileIcon (fileName) {
      const str = fileName.split('.');
      return fileTypeFormat(str[str.length - 1])
    },

    // 处理图片链接为富文本
    setImgUrl (content) {
      // 1. 首先检查 content 是否为字符串，如果不是，直接返回空字符串或进行其他处理
      if (typeof content !== 'string') {
        console.warn('setImgUrl 接收到的 content 不是一个字符串:', content);
        return ''; // 或者返回一个占位图片，例如: return '<p><img src="placeholder.png" /></p>';
      }

      if (this.isRichText(content)) {
        return graceRichText.format(content);
      } else {
        // 处理图片URL
        let processedUrl = content;

        // 处理没有域名的相对路径（以/uploads/开头）
        if (processedUrl.startsWith('/uploads/')) {
          processedUrl = 'https://chat.mfarmers.com:88' + processedUrl;
        } else if (processedUrl.startsWith('uploads/')) {
          processedUrl = 'https://chat.mfarmers.com:88/' + processedUrl;
        }

        // 处理有域名但端口是81的
        processedUrl = processedUrl.replace('http://chat.mfarmers.com:81/', 'https://chat.mfarmers.com:88/');

        // 处理有域名但没有端口的
        processedUrl = processedUrl.replace('http://chat.mfarmers.com/', 'https://chat.mfarmers.com:88/');

        // 移除thumb_前缀（如果存在）
        processedUrl = processedUrl.replace(/(\/)thumb_/g, '$1');

        // 确保URL使用HTTPS协议
        if (processedUrl.startsWith('http://')) {
          processedUrl = processedUrl.replace('http://', 'https://');
        }

        // 添加自适应样式
        return graceRichText.format(`<p><img src="${processedUrl}" style="max-width: 200rpx; height: auto;" /></p>`);
      }
    },

    // 判断是否为富文本
    isRichText (str) {
      return /<[a-z][\s\S]*>/i.test(str);
    },
    // 打开文件预览
    openDoc (item2) {
      const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
      const str = item2.name.split('.');
      const icon = str[str.length - 1];
      const that = this;
      let url = ''
      const xtoken = this.nextCloud.xtoken
      const fileName = encodeURIComponent(encodeURIComponent(item2.name)); // 双重编码
      const fileurl = encodeURIComponent(item2.url); // 单次编码
      if (type.indexOf(icon) != -1) {
        let previewUrl = ''
        if (xtoken) {
          previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${item2.nc_id ? item2.nc_id : ''}&fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`
        } else {
          previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${fileName}&type=mobile&user=${that.userStore.user.worker_id}&url=${fileurl}`
        }
        let encodedData = encodeURIComponent(JSON.stringify({ previewUrl }));
        url = `/pages/chat/message/common/previewDoc?data=${encodedData}`
      } else {
        url = `/pages/chat/message/common/downloadDoc?fileName=${fileName}&fileSize=${item2.formatSize}&url=${fileurl}`
      }

      uni.navigateTo({
        url: url
      })

    },
    handleSearch (keyword) {
      const hasKeyword = keyword && keyword.trim() !== '';
      const hasDateRange = this.selectedDateRange.length === 2;
      if (!hasKeyword && !hasDateRange) {
        this.searchResults = this.processAllMessages();
        return;
      }

      // 先过滤包含关键词的原始消息
      let filteredMessages = this.Chatarray.filter(item => {
        const searchableText = this.getSearchableText(item.content);
        return searchableText.toLowerCase().includes(keyword.toLowerCase());
      });

      // 如果有日期筛选，进一步筛选
      if (this.selectedDateRange.length === 2) {
        const [start, end] = this.selectedDateRange;
        const startDate = new Date(start);
        const endDate = new Date(end);
        endDate.setDate(endDate.getDate() + 1);

        filteredMessages = filteredMessages.filter(item => {
          const itemTime = new Date(item.send_time);
          return itemTime >= startDate && itemTime < endDate;
        });
      }

      // 保存原始Chatarray
      const originalChatArray = this.Chatarray;

      // 临时替换Chatarray为过滤后的结果
      this.Chatarray = filteredMessages;

      // 使用processAllMessages处理过滤后的消息
      this.searchResults = this.processAllMessages();

      // 恢复原始Chatarray
      this.Chatarray = originalChatArray;
    },
    // 从消息内容中提取可搜索的文本
    getSearchableText (content) {
      try {
        const parsed = JSON.parse(content);
        if (!Array.isArray(parsed)) return '';

        return parsed.map(msg => {
          if (msg.type === 'text') {
            return this.extractPureText(msg.content)
          } else if (msg.type === 'file') {
            return msg.name || ''; // 文件名也可搜索
          }
          return '';
        }).join(' ');
      } catch (e) {
        console.error('解析消息失败:', e);
        return '';
      }
    },
    // 搜索
    fillSearchInput (keyword) {
      this.searchResults = this.Chatarray.map(item => {
        const parsed = JSON.parse(item.content);
        const hasMatch = parsed.some(msg => {
          if (msg.type === 'text') {
            return this.extractPureText(msg.content)
          } else if (msg.type === 'file') {
            return msg.name.toLowerCase().includes(keyword.toLowerCase());
          }
          return false;
        });
        return hasMatch ? item : null;
      }).filter(item => item !== null);
    },
    processAllMessages () {
      return this.Chatarray.reduce((result, item) => {
        if (item.status == 12) {
          return result
        }
        let parsedContent;

        try {
          parsedContent = JSON.parse(item.content);
        } catch (e) {
          console.error('消息解析失败:', item.content);
          return result;
        }

        const baseData = {
          fromname: item.fromname,
          toname: item.to_name,
          sendtime: item.send_time,
          username: item.username,
          fromavatar: item.fromavatar
        };

        let processedMessages = [];

        if (
          Array.isArray(parsedContent) &&
          parsedContent.every(msg => msg.type === 'text')
        ) {
          const mergedHtml = parsedContent.map(msg => msg.content).join('');
          const pureText = this.extractPureText(mergedHtml);

          if (pureText) {
            processedMessages.push({
              ...baseData,
              type: 'text',
              content: this.replaceAtSpan(pureText),
              rawContent: pureText
            });
          }
        } else if (Array.isArray(parsedContent)) {
          processedMessages = parsedContent.map(msg => {
            if (!msg.content || (typeof msg.content === 'string' && !msg.content.trim())) {
              return null;
            }

            switch (msg.type) {
              case 'text':
                return {
                  ...baseData,
                  type: 'text',
                  content: this.replaceAtSpan(msg.content),
                  rawContent: msg.content
                };
              case 'img':
                return {
                  ...baseData,
                  type: 'img',
                  content: this.setImgUrl(msg.content),
                  rawContent: msg.content
                };
              case 'img/text':
                return {
                  ...baseData,
                  type: 'img/text',
                  content: this.setHtmlContent(msg.content),
                  rawContent: msg.content
                };
              case 'file':
                return {
                  ...baseData,
                  type: 'file',
                  name: msg.name,
                  url: msg.url,
                  formatSize: msg.formatSize,
                  rawContent: msg.content
                };
              case 'apply':
                const applyData = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'apply',
                  apply: {
                    id: applyData.apply_id,   // 存储 apply_id
                    title: applyData.title,
                    status: applyData.status,
                    detail: applyData.detail
                  }
                };
              case 'apply_urge':
                const applyurgeData = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'apply_urge',
                  content: {
                    id: applyurgeData.apply_id,
                    title: applyurgeData.title,
                    content: applyurgeData.content,
                  }
                };
              case 'apply_mention':
                const applymentionData = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'apply_mention',
                  content: {
                    id: applymentionData.apply_id,
                    title: applymentionData.title,
                    content: applymentionData.content,
                  }
                };
              case 'log':
                const log = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'log',
                  id: log.id,
                  content: {
                    title: log.title,
                    content: log.content,
                  }
                };
              case 'notice':
                const notice = JSON.parse(msg.content)
                return {
                  ...baseData,
                  type: 'notice',
                  id: notice.id,
                  content: {
                    title: notice.title,
                    content: notice.content,
                  }
                };
              default:
                return null;
            }
          }).filter(Boolean);
        } else if (parsedContent && parsedContent.type === 'text') {
          const raw = parsedContent.content;
          if (raw && raw.trim()) {
            processedMessages.push({
              ...baseData,
              type: 'text',
              content: this.replaceAtSpan(raw),
              rawContent: raw
            });
          }
        }

        return result.concat(processedMessages);
      }, []);
    },
    setHtmlContent (content) {
      try {
        // 处理图片URL
        let processedContent = content;

        // 处理没有域名的相对路径（以/uploads/或uploads/开头）
        processedContent = processedContent.replace(/(src=")(uploads\/)/g, '$1https://chat.mfarmers.com:88/$2');
        processedContent = processedContent.replace(/(src=")(\/uploads\/)/g, '$1https://chat.mfarmers.com:88$2');

        // 处理有域名但端口是81的
        processedContent = processedContent.replace(/http:\/\/chat\.mfarmers\.com:81\//g, 'https://chat.mfarmers.com:88/');

        // 处理有域名但没有端口的
        processedContent = processedContent.replace(/http:\/\/chat\.mfarmers\.com\//g, 'https://chat.mfarmers.com:88/');

        // 移除thumb_前缀（如果存在）
        processedContent = processedContent.replace(/(\/)thumb_/g, '$1');

        // 提取所有图片URL
        const imgTags = processedContent.match(/<img[^>]+>/g) || [];

        // 为每个图片添加自适应样式
        for (const imgTag of imgTags) {
          const newImgTag = imgTag.replace(
            /(<img[^>]*)(>)/,
            '$1 style="max-width: 200rpx; height: auto;"$2'
          );
          processedContent = processedContent.replace(imgTag, newImgTag);
        }

        // 使用graceRichText格式化
        return graceRichText.format(processedContent);
      } catch (e) {
        console.error(' 处理富文本内容失败:', e);
        return graceRichText.format(content);
      }
    },
    replaceAtSpan (html) {
      // 只匹配 class="mceNonEditable unfocusable" 的 span
      return html.replace(
        /<span\s+class="mceNonEditable unfocusable"(.*?)>(.*?)<\/span>/g,
        (match, attrs, inner) => {
          // 保留其他属性（例如 data=xxx）
          return `<span style="color: #409eff;"${attrs}>${inner}</span>`
        }
      );
    },
    extractPureText (html) {
      let pureText = '';

      // #ifdef H5
      const wrapper = document.createElement('div');
      wrapper.innerHTML = html;
      pureText = wrapper.textContent.trim();
      // #endif

      // #ifdef APP-PLUS
      // 替代 DOM 的正则方式：去掉所有标签，只留文本
      pureText = html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, '').trim();
      // #endif

      return pureText;
    },
    // 关闭聊天设置弹窗
    searchforclose () {
      uni.navigateBack();
    },

    // 名称超长处理
    showUserName (username) {
      if (username && username.length > 2) {
        return username.substr(1, 2);
      } else {
        return username;
      }
    },
    async onRefresh () {
      this.isRefreshing = true; // 开始刷新
      this.Chatarray = [];
      this.page = 1;
      this.noMore = false;
      // 调用获取消息的方法，带上查询条件
      await this.Getxiaoxi({
        searchKeyword: this.searchKeyword,
        selectedDateRange: this.selectedDateRange,
      });

      this.isRefreshing = false; // 结束刷新

    },
    async loadMore () {
      if (this.loading || this.noMore) return;
      this.page++;
      // 调用获取消息的方法，带上查询条件
      await this.Getxiaoxi({
        searchKeyword: this.searchKeyword,
        selectedDateRange: this.selectedDateRange,
      });
    },
    // 获取消息记录
    async Getxiaoxi ({ searchKeyword = '', selectedDateRange = [] } = {}) {
      if (this.loading) {
        return
      }

      this.loading = true;
      uni.showLoading({
        title: '加载中....'
      });
      const params = {
        'data[account]': this.imInfo.account,
        'data[token]': this.userInfo.token,
        'data[myAccount]': this.imInfo.account,
        'data[page]': this.page,
        'data[pageSize]': 30,
        'data[friendAccount]': this.friend.friend_account,
        url: 'index.php/users/Index/getChatRecord'
      }

      const msg = await chatApi(this.userInfo.token, params);

      if (msg.code == 200) {

        this.Chatarray = this.page == 1 ? msg.data.reverse() : [...this.Chatarray, ...msg.data.reverse()];

        if (msg.data.length == 0) {
          this.noMore = true;
        }
        this.isRefreshing = false;
        this.loading = false;
        uni.hideLoading();


        // 根据查询条件筛选结果
        this.handleSearch(searchKeyword);
      } else {
        this.loading = false;
        this.noMore = true;
        this.isRefreshing = false;
        uni.hideLoading();
      }

      uni.hideLoading();
    },
  }
}
</script>


<style lang="scss" scoped>
/* 加载中和无更多数据提示 */
.loading-text,
.no-more-text {
  margin-top: 20rpx;
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

// 聊天记录
.search-container {
  width: 100vw;
  background-color: #f3f3f3;
  overflow-y: hidden;

  .search-bar {
    padding: 20rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #eee;
  }

  .search-filter {
    display: flex;
    padding: 0 20rpx;
    margin-top: 10rpx;

    .filter-container {
      //#ifdef H5
      width: 61%;
      //#endif

      // #ifdef APP-PLUS
      width: 70%;
      // #endif
    }
  }


  .search-result {
    overflow-y: auto;

    .no-result {
      text-align: center;
      padding: 40rpx 0;
      color: #999;
      font-size: 26rpx;
    }

    .result-list {
      .result-item {
        border-radius: 20rpx;
        background-color: #ffffff;
        padding: 20rpx;
        margin-bottom: 20rpx;
        min-height: 80rpx;

        &:last-child {
          border-bottom: none;
        }

        .result-header {
          display: flex;
          align-items: center;
          margin-bottom: -30rpx;

          .result-avatar {
            margin-right: 20rpx;

            .avatar-circle {
              width: 80rpx;
              height: 80rpx;
              border-radius: 15%;
              background-color: #377fff;
              color: #fff;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 32rpx;
              font-weight: bold;
            }
          }

          .result-sender {
            flex: 1;
            display: flex;
            flex-direction: column;

            .sender-name {

              font-size: 28rpx;
              color: #333;
              font-weight: bold;
              margin-bottom: 5rpx;
            }

            .sender-to {
              font-size: 24rpx;
              color: #666;
              margin-bottom: 5rpx;
            }

            .sender-time {

              font-size: 22rpx;
              color: #999;
              text-align: right;
              position: relative;



              // #ifdef H5
              top: -3vh;
              // #endif

              // #ifdef APP-PLUS
              top: -2vh;

              // #endif
            }
          }
        }

        .result-content-box {
          padding-left: 100rpx; // 与头像对齐

          .result-content {
            font-size: 26rpx;
            color: #333;
            line-height: 1.5;
          }
        }
      }
    }
  }
}

.file-message {
  display: flex;
  line-height: 32rpx;
  width: 55vw;
  margin-top: 10rpx;

  .file-logo {
    margin-right: 20rpx;

    image {
      width: 50rpx;
    }
  }

  .file-name {
    font-weight: 500;
    font-size: 28rpx;

    text {
      font-size: 24rpx;
      color: #A4A6A8;
      font-weight: 400;
    }
  }
}


// 时间范围弹窗样式
.time-popup-content {
  padding: 30rpx;
  background-color: #fff;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .close-icon {
      font-size: 36rpx;
      color: #999;
    }
  }

  .popup-footer {
    margin-top: 20rpx;

    .u-button {
      width: 100%;
    }
  }
}

// 审批单样式
.chat-apply {
  margin-top: 40rpx;

}

.apply-card {
  .applytitle {
    display: flex;
    font-weight: 600;
    background-color: #fff2e0;
    margin-bottom: 1px;
    padding: 8px;
    border-radius: 10px 10px 0px 0px;
    color: #fd9100;

    .apply-status {
      //#ifdef H5
      margin-top: 2rpx;
      //#endif

      // #ifdef APP-PLUS
      margin-top: -2rpx;
      // #endif
      height: 20px;
      line-height: 20px;
      text-align: center;
      max-width: 120rpx !important;
      min-width: 100rpx !important;
      margin-left: 12rpx;
      font-size: 12px;
      font-weight: 500;
      border-radius: 8px;
      color: #fff;
    }

    /* 审批状态：0 待提交 / 待处理 */
    .applystatus-0 {
      color: #ff9800;
      border: 1px solid #ff9800;
    }

    /* 审批状态：1 审核中 */
    .applystatus-1 {
      color: #2196f3;
      border: 1px solid #2196f3;
    }

    /* 审批状态：2 已通过 */
    .applystatus-2 {
      color: #4caf50;
      border: 1px solid #4caf50;
    }

    /* 审批状态：3 已驳回 */
    .applystatus-3 {
      color: #f44336;
      border: 1px solid #f44336;
    }

    /* 审批状态：4 已撤销 */
    .applystatus-4 {
      color: #9e9e9e;
      border: 1px solid #9e9e9e;
    }

  }

  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.10);

  .apply-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;

    .apply-title {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }


  }

  .apply-detail {
    margin-bottom: 10rpx;

    .apply-detail-item {
      display: flex;
      font-size: 26rpx;
      margin-bottom: 6rpx;

      .label {
        color: #666;
        width: 140rpx;
      }

      .value {
        color: #333;
        flex: 1;
      }
    }
  }

  .apply-footer {
    margin: 0 auto;
    width: 100%;
    background-color: #f3f3f4;
    margin-top: 10px;
    text-align: center;
    font-size: 28rpx;
    color: #0066ff;
    padding: 6px 0;
    border-radius: 8px;
    cursor: pointer;
    user-select: none;
    font-weight: 700;
  }
}


.apply_urge {
  .applyurgetitle {
    font-weight: 600;
    margin-bottom: 1px;
    border-radius: 10px 10px 0px 0px;
  }

  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.10);

  .applyurge-header {
    padding: 4px 5px 0 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10rpx;
    border: 1px solid #ddd;
    border-radius: 5px;

    .applyurge-title {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }
  }

}


.apply_mention {
  display: flex;
  justify-content: center; // 水平居中
  width: 100%;

  .applymention-card {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 8px;
    margin: 8px 0;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.10);

    .applymention-Title {
      font-weight: 600;
      background-color: #fff2e0;
      margin-bottom: 1px;
      padding: 8px;
      border-radius: 10px 10px 0px 0px;
      color: #fd9100;
    }

    .applymentiontitle {
      font-weight: 600;
      padding: 4px;
    }

    .applymention-header {
      padding: 8px;
      border-radius: 5px;
      padding: 0 5px;
      display: flex;
      padding-top: 3px;
      border-radius: 5px;

    }
  }
}

/* 日志消息样式 */
.chat-log {
  .log-card {
    position: relative;
    background: #c9e7ff;
    border-radius: 16rpx;
    padding: 2rpx;
    margin: 8rpx auto;
    width: 450rpx;
  }

  .log-bg {
    width: 95.5%;
    left: 0;
    top: 0;
    border-radius: 10px 10px 0px 0px;
    position: absolute;
    height: 30px;
    font-weight: bold;
    line-height: 30px;
    background-color: #e0ecff;
    color: #016fff;
    padding-left: 10px;
  }

  .log-title {
    margin-top: 60rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 15rpx;
    padding-left: 10px;
  }

  .log-content {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 40rpx;
    padding-left: 10px;
  }

  .log-content ::v-deep p {
    margin: 0 0 10rpx 0;
    line-height: 1.6;
  }

  .log-content ::v-deep p:last-child {
    margin-bottom: 0;
  }
}

/* 通知消息样式 */
.chat-notice {
  .public-notice-card {
    background: #c9e7ff;
    border-radius: 16rpx;
    width: 450rpx;
    margin: 8rpx auto;
    padding: 2rpx;
  }

  .notice-tag {
    color: #66a6ff;
    margin-bottom: 10rpx;
    padding-left: 10px;
  }

  .notice-title {
    font-size: 30rpx;
    font-weight: bold;
    margin-bottom: 15rpx;
    color: #333;
    padding-left: 10px;
  }

  .notice-image {
    position: relative;
    margin-bottom: 15rpx;

    .image-text {
      position: absolute;
      left: 30rpx;
      top: 50%;
      transform: translateY(-50%);
      color: #fff;
      font-size: 36rpx;
    }

  }

  .notice-image image {
    width: 100%;
    border-radius: 8rpx;
  }

  .notice-content {
    font-size: 26rpx;
    color: #333;
    margin-bottom: 20rpx;
    line-height: 40rpx;
    padding-left: 10px;
  }
}

.detail-btn {
  margin: 0 auto;
  width: 100%;
  background-color: #f3f3f4;
  margin-top: 10px;
  text-align: center;
  font-size: 28rpx;
  color: #0066ff;
  padding: 6px 0;
  border-radius: 8px;
  cursor: pointer;
  user-select: none;
  font-weight: 700;
}
</style>
